
import React, { useState, useEffect, useRef } from 'react';
import { View, StyleSheet, Dimensions, Text, TouchableOpacity, Animated, Image } from 'react-native';
import Video from 'react-native-video';
import Adapt from '../../ulits/Adapt';
import { getAdvList, toggleFollow, addDynamic, deleteDynamic } from '../../ulits/instance';
import AsyncStorage from '@react-native-async-storage/async-storage';
import { useNavigation, useIsFocused } from '@react-navigation/native';

const { width: SCREEN_WIDTH, height: SCREEN_HEIGHT } = Dimensions.get('window');
export default function VideoGallery() {
    const navigation = useNavigation();
    const isFocused = useIsFocused();
    const [videoList, setVideoList] = useState([]);
    const [currentIndex, setCurrentIndex] = useState(0);
    const [isPlaying, setIsPlaying] = useState(true);
    const [progress, setProgress] = useState(0);
    const [showControls, setShowControls] = useState(false);
    const videoRef = useRef(null);
    const containerRef = useRef(null);
    const controlsTimeout = useRef(null);
    const [isSwiping, setIsSwiping] = useState(false);
    const [startY, setStartY] = useState(0);
    const [swipeOffset, setSwipeOffset] = useState(0);
    const translateY = useRef(new Animated.Value(0)).current;
    const lastSwipeTime = useRef(0);
    const [userData, setUserData] = useState(null);
    const [isFollowing, setIsFollowing] = useState(false);
    const [isUpdating, setIsUpdating] = useState(false); // 防止重复操作

    const tiao = () => {
        navigation.navigate('Upload');
    };

    const tiao1 = () => {
        navigation.navigate('Chat');
    };

    const getUserData = async () => {
        try {
            const data = await AsyncStorage.getItem('userData');
            if (data) {
                const parsedData = JSON.parse(data);
                setUserData(parsedData);
                console.log('从本地存储获取的用户数据:', parsedData);
            } else {
                console.log('本地存储中没有用户数据');
            }
        } catch (error) {
            console.error('获取用户数据失败:', error);
        }
    };

    const getVideoList = async () => {
        try {
            const { data } = await getAdvList();
            const formattedList = Array.isArray(data) ? data : Object.values(data);
            const enrichedList = formattedList.map(item => ({
                ...item,
                q: item.q || { 
                    img: 'https://ts1.tc.mm.bing.net/th/id/OIP-C.at5bvJB37cIcJ0WWvSmK0AHaHa?w=193&h=211&c=8&rs=1&qlt=90&o=6&dpr=1.5&pid=3.1&rm=2',
                    guan: item.q?.guan || '关注'
                }
            }));
            setVideoList(enrichedList);
            setIsFollowing(enrichedList[currentIndex]?.q?.guan === '已关注');
            console.log('格式化后的视频列表:', enrichedList);
        } catch (error) {
            console.error('获取视频列表失败:', error);
        }
    };
    console.log(isFocused);
    useEffect(() => {
        if (isFocused) {
            getVideoList();
            getUserData();
        }
    }, [isFocused]);

    useEffect(() => {
        setIsFollowing(videoList[currentIndex]?.q?.guan === '已关注');
    }, [currentIndex, videoList]);

    const handleTimeUpdate = (data) => {
        if (videoRef.current) {
            const currentProgress = (data.currentTime / data.duration) * 100;
            setProgress(currentProgress);
        }
    };

    const handleTouchStart = (e) => {
        setStartY(e.nativeEvent.pageY);
        setIsSwiping(false);
        setSwipeOffset(0);
        translateY.setValue(0);
        showControlsTemporarily();
    };

    const handleTouchMove = (e) => {
        const y = e.nativeEvent.pageY;
        const dy = y - startY;

        if (Math.abs(dy) > Adapt.adapt(5)) {
            setIsSwiping(true);
            setSwipeOffset(dy);
            Animated.timing(translateY, {
                toValue: dy * 0.5,
                duration: 0,
                useNativeDriver: true,
            }).start();
        }
    };

    const handleTouchEnd = (e) => {
        const currentTime = Date.now();
        if (currentTime - lastSwipeTime.current < 300) {
            Animated.spring(translateY, {
                toValue: 0,
                useNativeDriver: true,
            }).start();
            setIsSwiping(false);
            return;
        }

        if (!isSwiping) {
            togglePlayPause();
            Animated.spring(translateY, {
                toValue: 0,
                useNativeDriver: true,
            }).start();
            return;
        }

        const endY = e.nativeEvent.pageY;
        const dy = endY - startY;
        const swipeThreshold = Adapt.adapt(30);
        const velocity = Math.abs(dy / (Date.now() - lastSwipeTime.current + 1));

        if (Math.abs(dy) > swipeThreshold || velocity > 0.1) {
            if (dy > 0 && currentIndex > 0) {
                switchVideo(currentIndex - 1);
            } else if (dy < 0 && currentIndex < videoList.length - 1) {
                switchVideo(currentIndex + 1);
            }
            lastSwipeTime.current = currentTime;
        }

        Animated.spring(translateY, {
            toValue: 0,
            useNativeDriver: true,
        }).start();
        setIsSwiping(false);
    };

    const togglePlayPause = () => {
        if (videoRef.current) {
            setIsPlaying(!isPlaying);
        }
        showControlsTemporarily();
    };

    const switchVideo = (newIndex) => {
        setCurrentIndex(newIndex);
        setIsPlaying(true);
        setProgress(0);

        setTimeout(() => {
            if (videoRef.current) {
                videoRef.current.seek(0);
            }
        }, 300);
    };

    const handleVideoEnd = () => {
        if (videoRef.current) {
            videoRef.current.seek(0);
            setIsPlaying(true);
        }
    };

    const showControlsTemporarily = () => {
        setShowControls(true);
        clearTimeout(controlsTimeout.current);
        controlsTimeout.current = setTimeout(() => {
            setShowControls(false);
        }, 3000);
    };

    const handleProgressClick = (e) => {
        const pos = e.nativeEvent.locationX / Adapt.getScreenWidth();
        const video = videoRef.current;
        if (video) {
            video.seek(pos * video.duration);
            setProgress(pos * 100);
        }
        showControlsTemporarily();
    };

    const currentVideo = videoList[currentIndex] || {};
    console.log('当前视频:', currentVideo);
    console.log('当前:', videoList);

    const handleFollow = async () => {
        if (!userData?._id || !currentVideo?._id || isUpdating) {
            console.error('操作条件不足或正在更新:', { userData, currentVideo, isUpdating });
            return;
        }
        setIsUpdating(true);
        try {
            if (!isFollowing) {
                // 点击“关注”时，切换为“已关注”并添加动态
                const toggleResponse = await toggleFollow({ advId: currentVideo._id });
                if (toggleResponse.code === 200) {
                    const updatedList = videoList.map((item, index) =>
                        index === currentIndex ? { ...item, q: { ...item.q, guan: toggleResponse.data.guan } } : item
                    );
                    setVideoList(updatedList);
                    setIsFollowing(true);
                    console.log('关注状态切换成功:', toggleResponse.data.guan);

                    const addResponse = await addDynamic(currentVideo.q._id);
                    if (addResponse.code === 200) {
                        console.log('动态添加成功:', addResponse.msg);
                    } else {
                        console.error('动态添加失败:', addResponse.message);
                    }
                }
            } else {
                // 点击“已关注”时，切换为“关注”并删除动态
                const toggleResponse = await toggleFollow({ advId: currentVideo._id });
                if (toggleResponse.code === 200) {
                    const updatedList = videoList.map((item, index) =>
                        index === currentIndex ? { ...item, q: { ...item.q, guan: toggleResponse.data.guan } } : item
                    );
                    setVideoList(updatedList);
                    setIsFollowing(false);
                    console.log('关注状态切换成功:', toggleResponse.data.guan);

                    const deleteResponse = await deleteDynamic(currentVideo.q._id);
                    if (deleteResponse.code === 200) {
                        console.log('动态删除成功:', deleteResponse.msg);
                    } else {
                        console.error('动态删除失败:', deleteResponse.message);
                    }
                }
            }
        } catch (error) {
            console.error('操作失败:', error.response?.data || error.message);
        } finally {
            setIsUpdating(false);
        }
    };

    return (
        <View style={styles.container}>
            <Animated.View
                ref={containerRef}
                style={[styles.videoContainer, { transform: [{ translateY }] }]}
                onTouchStart={handleTouchStart}
                onTouchMove={handleTouchMove}
                onTouchEnd={handleTouchEnd}
            >
                {currentVideo ? (
                    <View style={styles.videoItem}>
                        <Video
                            ref={videoRef}
                            source={{ uri: `http://192.168.9.209:3000${currentVideo.url}` }}
                            style={styles.video}
                            playsInSilentModeEnabled={false}
                            playInBackground={false}
                            repeat={false}
                            paused={!isPlaying}
                            onEnd={handleVideoEnd}
                            onProgress={handleTimeUpdate}
                            resizeMode="cover"
                        />
                        <Text style={styles.titleTex}>
                                                    @{currentVideo.q?.username || '无用户'}
                                                </Text>
                        <Text style={styles.titleText}>
                            {currentVideo.title || '无标题'}
                        </Text>
                        <View style={styles.avatarContainer}>
                            <TouchableOpacity onPress={tiao1}>
                                <Image
                                    source={{ uri: currentVideo.q?.img || 'https://ts1.tc.mm.bing.net/th/id/OIP-C.at5bvJB37cIcJ0WWvSmK0AHaHa?w=193&h=211&c=8&rs=1&qlt=90&o=6&dpr=1.5&pid=3.1&rm=2' }}
                                    style={styles.avatar}
                                />
                            </TouchableOpacity>
                            <TouchableOpacity style={styles.followButton} onPress={handleFollow}>
                                <Text style={styles.followButtonText}>
                                    {isFollowing ? '已关注' : '关注'}
                                </Text>
                            </TouchableOpacity>
                        </View>
                    </View>
                ) : (
                    <Text style={styles.noVideoText}>暂无视频</Text>
                )}

                <View
                    style={{
                        ...styles.controls,
                        opacity: showControls ? 1 : 0,
                    }}
                >
                    <View style={styles.progressBar} onTouchEnd={handleProgressClick}>
                        <View style={{ ...styles.progress, width: `${progress}%` }} />
                    </View>

                    <View style={styles.playButton} onTouchEnd={togglePlayPause}>
                        {isPlaying ? (
                            <Text style={styles.controlText}>||</Text>
                        ) : (
                            <Text style={styles.controlText}>▶</Text>
                        )}
                    </View>
                </View>
            </Animated.View>

            <TouchableOpacity style={styles.uploadButton} onPress={tiao}>
                <Text style={styles.uploadButtonText}>+</Text>
            </TouchableOpacity>
        </View>
    );
}

const styles = StyleSheet.create({
    container: {
        flex: 1,
        backgroundColor: 'black',
    },
    videoContainer: {
        flex: 1,
        backgroundColor: 'black',
    },
    videoItem: {
        width: '100%',
        height: '100%',
    },
    video: {
        width: '100%',
        height: '100%',
        backgroundColor: 'black',
    },
    controls: {
        position: 'absolute',
        bottom: 0,
        left: 0,
        width: '100%',
        padding: Adapt.adapt(10),
        backgroundColor: 'rgba(0, 0, 0, 0.5)',
        zIndex: 10,
    },
    progressBar: {
        width: '100%',
        height: Adapt.adapt(4),
        backgroundColor: 'rgba(255, 255, 255, 0.3)',
        borderRadius: Adapt.adaptRadius(2),
        marginBottom: Adapt.adaptMargin(10),
    },
    progress: {
        height: '100%',
        backgroundColor: 'red',
        borderRadius: Adapt.adaptRadius(2),
    },
    playButton: {
        alignItems: 'center',
        justifyContent: 'center',
    },
    controlText: {
        fontSize: Adapt.adaptFontSize(24),
        color: 'white',
    },
    uploadButton: {
        position: 'absolute',
        bottom: Adapt.adapt(20),
        alignSelf: 'center',
        width: Adapt.adapt(50),
        height: Adapt.adapt(50),
        borderRadius: Adapt.adaptRadius(25),
        backgroundColor: '#ff2d55',
        alignItems: 'center',
        justifyContent: 'center',
        zIndex: 999,
    },
    uploadButtonText: {
        fontSize: Adapt.adaptFontSize(30),
        color: 'white',
        fontWeight: 'bold',
    },
    avatarContainer: {
        position: 'absolute',
        right: Adapt.adapt(10),
        top: '50%',
        transform: [{ translateY: Adapt.adapt(-60) }],
        alignItems: 'center',
        zIndex: 999,
    },
    avatar: {
        width: Adapt.adapt(40),
        height: Adapt.adapt(40),
        borderRadius: Adapt.adaptRadius(20),
        backgroundColor: '#ccc',
    },
    followButton: {
        marginTop: Adapt.adaptMargin(10),
        backgroundColor: '#ff2d55',
        paddingVertical: Adapt.adapt(5),
        paddingHorizontal: Adapt.adapt(10),
        borderRadius: Adapt.adaptRadius(5),
    },
    followButtonText: {
        color: 'white',
        fontSize: Adapt.adaptFontSize(14),
        fontWeight: 'bold',
    },
    titleText: {
        position: 'absolute',
        bottom: Adapt.adapt(20),
        left: Adapt.adapt(10),
        backgroundColor: 'rgba(128, 128, 128, 0.8)',
        color: 'white',
        padding: Adapt.adapt(5),
        borderRadius: Adapt.adaptRadius(5),
        zIndex: 999,
    },
titleTex: {
        position: 'absolute',
        bottom: Adapt.adapt(50),
        left: Adapt.adapt(10),
        backgroundColor: 'rgba(128, 128, 128, 0.8)',
        color: 'white',
        padding: Adapt.adapt(5),
        borderRadius: Adapt.adaptRadius(5),
        zIndex: 999,
    },
    noVideoText: {
        color: 'white',
        fontSize: Adapt.adaptFontSize(18),
        textAlign: 'center',
        marginTop: '50%',
    },
});
